
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @ClassName fileReplace
 * @Description T0D0
 * @Author ykq11
 * @Date 2024/2/20 22:31
 * @Version 1.0
 **/
public class ReplaceKeywordInFile {
    public static void defectOperator(String keyword, String defectTargetPath, String defectMoveTargetPath,
                                                         String defectReplaceWork, String defectKeywordToReplace, Boolean isDelete){

        // 输入目录路径和关键字
        Path sourceDirectory = Paths.get(defectTargetPath);
        // 输出目录
        Path destinationDirectory = Paths.get(defectMoveTargetPath);
        String keywordToReplace =defectReplaceWork;
        String replaceWord = defectKeywordToReplace;
        AtomicReference<String> operaFilePath= new AtomicReference<>("");
        try {
            // 遍历目录
            Files.walk(sourceDirectory)
                    .filter(path -> path.toString().endsWith(keyword))
                    .forEach(defectFilePath -> {
                        try {
                            // 读取文件内容
                            List<String> lines = Files.readAllLines(defectFilePath);

                            // 判断文件是否包含关键字
                            boolean containsKeyword = lines.stream().anyMatch(line -> line.contains(keywordToReplace));

                            if (containsKeyword) {
                                // 替换关键字
                                List<String> updatedLines = lines.stream()
                                        .map(line -> line.replace(keywordToReplace, replaceWord))
                                        .collect(Collectors.toList());
                                // 写入更新后的内容到文件
                                Path updatedFilePath = destinationDirectory.resolve(defectFilePath.getFileName());
                                Files.write(updatedFilePath, updatedLines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
                                if (isDelete) {
                                    boolean delete = new File(String.valueOf(defectFilePath)).delete();
                                    modifyFile(defectFilePath.toString());
                                    System.out.println(defectFilePath+"file operation sucess：" + destinationDirectory);
                                }
                            } else {
                                System.out.println("file " + defectFilePath + "Does not contain the keyword, no need for processing。");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static  void modifyFile(String path) {
        ConfigStrategy build = ConfigStrategy.build();
        if (StringUtils.isNotEmpty(path)) {
            String[] split = path.split("\\\\");
            String filePath = split[split.length - 1];
            String[] split1 = filePath.split("\\.");
            String macroTargetPath = build.getProperty("macroTargetPath");
            StringBuilder macroPath = new StringBuilder();
            macroPath.append(macroTargetPath).append("/");
            for (int i = 0; i < split1.length-2; i++) {
                macroPath.append(split1[i]).append("/");
            }
            if (new File(String.valueOf(macroPath)).exists()) {
                directModify(".macro",String.valueOf(macroPath),build.getProperty("macroMoveTargetPath"),build.getProperty("macroReplaceWork")
                        ,build.getProperty("macroKeywordToReplace"),false );
            }
        }
    }

    public static void directModify(String keyword, String defectTargetPath, String defectMoveTargetPath,
                                    String defectReplaceWork, String defectKeywordToReplace, Boolean isDelete){
        // 输入目录路径和关键字
        Path sourceDirectory = Paths.get(defectTargetPath);
        // 输出目录
        Path destinationDirectory = Paths.get(defectMoveTargetPath);
        String keywordToReplace =defectReplaceWork;
        String replaceWord = defectKeywordToReplace;
        try {
            // 遍历目录
            Files.walk(sourceDirectory)
                    .filter(path -> path.toString().endsWith(keyword))
                    .forEach(defectFilePath -> {
                        try {
                            // 读取文件内容
                            List<String> lines = Files.readAllLines(defectFilePath);
                            // 判断文件是否包含关键字
                            boolean containsKeyword = lines.stream().anyMatch(line -> line.contains(keywordToReplace));
                            if (containsKeyword) {
                                // 替换关键字
                                List<String> updatedLines = lines.stream()
                                        .map(line -> line.replace(keywordToReplace, replaceWord))
                                        .collect(Collectors.toList());
                                // 写入更新后的内容到文件
                                Path updatedFilePath = destinationDirectory.resolve(defectFilePath.getFileName());
                                Files.write(updatedFilePath, updatedLines, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
                                System.out.println("文件处理成功，已替换关键字并移动到目录：" + destinationDirectory);
                            } else {
                                System.out.println("文件 " + defectFilePath + " 不包含关键字，无需处理。");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
